package com.sdusoft.toolbox;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class LinkTool {

	private final static Pattern url_pattern = Pattern
			.compile("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?");
	private final static String rootDomain = "coder007.com";
	private final static String defaultUrl = "http://www.coder007.com/";

	/**
	 * 自动为文本中的url生成链接
	 * 
	 * @param txt
	 * @param only_our 
	 * @return
	 */
	public static String autoMakeLink(String txt, boolean only_our) {
		StringBuilder html = new StringBuilder();
		int lastIdx = 0;
		Matcher matchr = url_pattern.matcher(txt);
		while (matchr.find()) {
			String str = matchr.group();
			html.append(txt.substring(lastIdx, matchr.start()));
			if (!only_our
					|| StringUtils.containsIgnoreCase(str, rootDomain))
				html.append("<a href='" + str + "'>" + str + "</a>");
			else
				html.append(str);
			lastIdx = matchr.end();
		}
		html.append(txt.substring(lastIdx));
		return html.toString();
	}

	/**
	 * 返回一个url地址 
	 * 
	 * @return
	 */
	public static String home() {
		return defaultUrl;
	}

	public static String home(String string) {
		return null;
	}

	// param like: file/download?id=
	public static String action(String string) {
		return defaultUrl + "action/" + string;
	}

	public static Object encode_url(String action) {
		try {
			return URLEncoder.encode(action, "UTF-8");
		} catch (Exception e) {
			return "";
		}
	}
	
	public static List<String> testList(){
		return Arrays.asList("aaa","bb");
	}

}
